//
//  ChatViewController.m
//  XTXOneToOne
//
//  Created by Canny on 2018/11/4.
//  Copyright © 2018年 WK. All rights reserved.
//

#import "ChatViewController.h"
#import "SocketRocketUtility.h"
#import "SDChatDataModel.h"
/* 聊天内容模型 */

#import "SDChatMessage.h"
#import "SDChatDetail.h"
#import "SDChatDetailFrame.h"
#import "SDChatDetailTableViewCell.h"


/* 聊天内容View */
#import "SDChatInputView.h" //输入view
#import "SDChatDetailTableView.h" //列表


@interface ChatViewController ()
<

UIGestureRecognizerDelegate,
SDChatInputViewDelegate,
SDChatDetailTableViewLongPress,
UIScrollViewDelegate

>



@property (nonatomic,strong)UILabel * status;
@property (nonatomic,strong)UILabel * symbol;
@property (nonatomic,strong)UILabel * money;
@property (nonatomic,strong)UILabel * time;
@property (nonatomic,strong)UILabel * lab2;
@property (nonatomic,strong) NSTimer *orderTimer;

@property (nonatomic,assign)NSInteger T;

@property (nonatomic,strong)UITextField *chatTextFiled;
@property (nonatomic,strong)SDChatDetailTableView * chatTableView;

/**
 *  是否正在切换键盘
 */
@property (nonatomic, assign, getter = isChangingKeyboard) BOOL changingKeyboard;


/**
 聊天弹出的view
 */
@property (nonatomic,strong)SDChatInputView *chatInputView;


#pragma mark -  列表上啦加载更多
/**
 下拉加载更多
 */
@property (nonatomic,assign) BOOL isRefresh;

/**
 菊花
 */
@property (nonatomic,strong) UIActivityIndicatorView * activity;

/**
 聊天列表加载的小菊花view
 */
@property (nonatomic,strong) UIView *headView;





@end

@implementation ChatViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self setProperty];
    [self createUI];

}

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarHidden = NO;
    
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.navigationBarHidden=YES;
    
    
    //系统键盘谈起通知
    [[NSNotificationCenter defaultCenter] addObserver:self.chatInputView selector:@selector(systemKeyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    
    //自定义键盘,系统键盘
    [[NSNotificationCenter defaultCenter] addObserver:self.chatInputView selector:@selector(keyboardResignFirstResponder:) name:SDChatKeyboardResign object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHiden:) name:UIKeyboardWillHideNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(SRWebSocketDidReceiveMsg:) name:Chat_kWebSocketdidReceiveMessageNote object:nil];

    
    [self GetOtcorderOrderStatus];
    [self GetOtcorderFindorder];
    
    [self loadHistoryChatData];
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:Chat_kWebSocketdidReceiveMessageNote object:nil];
    [self stopTimer];
}

- (void)SRWebSocketDidReceiveMsg:(NSNotification *)note {
    //收到服务端发送过来的消息
    //    NSString * message = note.object;
    //    NSLog(@"-----收到服务端发送过来的消息--------%@",message);

    [self.chatTableView reloadData];
    [self scrollTableToFoot:NO];

    //    [self.chatTableView setContentOffset:CGPointMake(0, CGFLOAT_MAX)];

    
}
#pragma mark  - 滑到最底部
- (void)scrollTableToFoot:(BOOL)animated
{
    NSInteger s = [self.chatTableView numberOfSections];  //有多少组
    if (s<1) return;  //无数据时不执行 要不会crash
    NSInteger r = [self.chatTableView numberOfRowsInSection:s-1]; //最后一组有多少行
    if (r<1) return;
    NSIndexPath *ip = [NSIndexPath indexPathForRow:r-1 inSection:s-1];  //取最后一行数据
    [self.chatTableView scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionBottom animated:animated]; //滚动到最后一行
}


#pragma mark-开启websocket
-(void)loadHistoryChatData{
    
    SocketRocketUtility * SK = [SocketRocketUtility instance];
    [SK SRWebSocketOpenWithURLString:WEBSOCKET_API_2];
    [self OpenWebScocket];

}



-(void)OpenWebScocket{
    [self sendData];
    [self performSelector:@selector(sendData) withObject:nil afterDelay:1];
//    [self performSelector:@selector(sendData) withObject:nil afterDelay:10];
    
}

-(void)sendData{
    SocketRocketUtility * SK =[SocketRocketUtility instance];
    
    NSDictionary * dic =
      @{
          @"cmd": @"register",
          @"args": @{
                  @"access_token":[LoginModel GetValue:DL_token],
                  @"order_id":_order_id
                  }
          
      };
    
    NSData *data= [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
    [SK sendData:data];
  
    
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    SocketRocketUtility * SK =[SocketRocketUtility instance];
    [SK SRWebSocketClose];
}

- (void)keyboardWillBeHiden:(NSNotification *)notification
{
    [_chatInputView customKeyboardMove:G_SCREENHEIGHT - 50];

}

-(void)setProperty{
    SDChatDataModel * SD = [SDChatDataModel sharedSDChatDataModel];
    [SD.dataSource removeAllObjects];
    
    self.view.backgroundColor=RGB(255, 255, 255);
    [UIApplication sharedApplication].statusBarHidden = NO;
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.navigationBarHidden=YES;
    
}

-(void)createUI{
    
    [self createHeaderView];

    /*
     * tab
     */
    [self.bgView addSubview:self.chatTableView];
    
//    /*
//     * 加载历史数据
//     */
//    [self loadHistory];
    
    /*
     * 传值
     */
//    self.chatTableView.dataArray = self.dataArr;
    
    /*
     * 刷新
     */
    [self.chatTableView reloadData];
    
    
    /*
     * 添加键盘
     */
    [self.view addSubview:self.chatInputView];

    UITapGestureRecognizer *singleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeKeyboard:)];
    singleTapGesture.numberOfTapsRequired = 1;
    singleTapGesture.cancelsTouchesInView = NO;
    [self.bgView  addGestureRecognizer:singleTapGesture];
    
}

#pragma mark - gesture actions
- (void)closeKeyboard:(UITapGestureRecognizer *)recognizer {
    [self.view endEditing:YES];
    [self inputViewScrollToBottom];

}

-(UIView *)headView{
    if (!_headView){
        _headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,G_SCREENWIDTH, 40)];
        _headView.backgroundColor = [UIColor clearColor];
        self.activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        self.activity.frame = CGRectMake(_headView.frame.size.width/2, _headView.frame.size.height/2, 20, 20);
        [_headView addSubview:_activity];
        
        _headView.hidden = YES;
    }
    return _headView;
}

-(SDChatDetailTableView *)chatTableView{
    if(!_chatTableView){
        _chatTableView = [[SDChatDetailTableView alloc] initWithFrame:CGRectMake(0,85, G_SCREENWIDTH, G_SCREENHEIGHT-85-kStatusBarAndNavigationBarHeight-50) style:UITableViewStyleGrouped];
        _chatTableView.sdLongDelegate=self;
        _chatTableView.tableHeaderView = self.headView;
        _chatTableView.backgroundColor=[UIColor whiteColor];
        _chatTableView.sectionFooterHeight = 300;
    }
    return _chatTableView;
}


// 输入view
-(SDChatInputView *)chatInputView{
    if (!_chatInputView){
        _chatInputView =[[SDChatInputView alloc]initWithFrame:CGRectMake(0,G_SCREENHEIGHT-50, G_SCREENWIDTH, kInputViewHeight)];
        _chatInputView.backgroundColor=[UIColor whiteColor];
        _chatInputView.sd_delegate=self;
    }
    return _chatInputView;
}



#pragma mark - 监听键盘弹出方法
- (void)sd_observerKeyboardFrameChange{
    
    [[NSNotificationCenter defaultCenter] addObserverForName: UIKeyboardWillChangeFrameNotification
     
    object:nil
    queue: [NSOperationQueue mainQueue]
    usingBlock:^(NSNotification * _Nonnull note) {
                                                      //
        
        NSLog(@"%s, line = %d,note =%@", __FUNCTION__, __LINE__, note);
                                                      
        
        CGFloat keyboardHeight = [note.userInfo[@"UIKeyboardBoundsUserInfoKey"] CGRectValue].size.height;
                                                      
        
        CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
                                                      

        
        [self sd_scrollToBottomWithAnimated:YES];
                                                      
        
        SDLog(@"键盘之后View:%@",NSStringFromCGRect(self.view.frame));
                                                      
        
        [UIView animateWithDuration:duration animations:^{
            
            [self.chatTableView setNeedsLayout];
            
        }];
        
    }];
    
}


#pragma mark - SDChatDetailTableViewDelegate
-(void)SDChatDetailTableView:(id)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.chatInputView.chatText resignFirstResponder];
    [self inputViewScrollToBottom];
}


/**
 键盘消失inputView在屏幕底部
 */
-(void)inputViewScrollToBottom{
    CGFloat chatInputHeight =CGRectGetHeight(self.chatInputView.frame);
    self.chatInputView.frame =CGRectMake(0,G_SCREENHEIGHT-(chatInputHeight-keyBoardDefaultHeight), G_SCREENWIDTH, chatInputHeight);
    
    [self sd_scrollToBottomWithAnimated:YES];
}


-(void)SDChatDetailTableViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView.contentOffset.y<=0  && self.isRefresh==NO)
    {
        //        [self setChatNetWorkMoreHistoryMsg];
    }
}

#pragma mark - chatInputViewDelegate

/**
 添加文件按钮监听

 @param sender  添加文件按钮监听
 */
-(void)SDChatInputViewAddFileClicked:(UIButton *)sender{
    SDLog(@"添加图片");
    
    
    
    
}


/**
 添加表情按钮监听
 
 @param sender 添加表情按钮监听
 */
-(void)SDChatInputViewAddFaceClicked:(UIButton *)sender{
    SDLog(@"添加表情");
    SDLog(@"self.frame.input:%@",NSStringFromCGRect(self.chatInputView.frame));
    
}

-(void)SDChatInputView:(SDChatInputView *)chatInputView sendTextMessage:(NSString *)textMessage{
    
    NSString * To = [NSString stringWithFormat:@"%@",self.FindOrderModel.bill_user_id];
    if ([To isEqualToString:[LoginModel GetValue:DL_user_id]]) {
        To = [NSString stringWithFormat:@"%@",self.FindOrderModel.user_id];
    }
    NSDictionary * Dic =@{
                             @"args":
                                @{
                                    @"from":[LoginModel GetValue:DL_user_id],
                                    @"to":To,
                                    @"order_id":self.FindOrderModel.ID,
                                    @"content":textMessage
                                 },
                              @"cmd":@"message"
                          };

    SocketRocketUtility * SK =[SocketRocketUtility instance];
    
    NSData *data= [NSJSONSerialization dataWithJSONObject:Dic options:NSJSONWritingPrettyPrinted error:nil];
    
    [SK sendData:data];
    
    
    NSDictionary *dic =@{@"content":textMessage,@"id":@"1",@"sender":@"1",@"create_time":[self getCurrentTimes],@"msgType":@"0",@"msgType":@"0"};
    SDChatMessage *msg =[SDChatMessage chatMessageWithDic:dic];
    msg.sender = @"1";
    msg.type = 0;
    SDChatDetail *chat =[SDChatDetail sd_chatWith:msg];
    SDChatDetailFrame *chatFrame =[[SDChatDetailFrame alloc]init];
    chatFrame.chat=chat;
    
    SDChatDataModel * SD = [SDChatDataModel sharedSDChatDataModel];
    [SD.dataSource addObject:chatFrame];
    
    
    [self.chatTableView reloadData];
    [self sd_scrollToBottomWithAnimated:YES];
//    [self.chatTableView setContentOffset:CGPointMake(0, CGFLOAT_MAX)];

    
    
}

//获取当前的时间

-(NSString*)getCurrentTimes{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    
    //现在时间,你可以输出来看下是什么格式
    
    NSDate *datenow = [NSDate date];
    
    //----------将nsdate按formatter格式转成nsstring
    
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    
    NSLog(@"currentTimeString =  %@",currentTimeString);
    
    return currentTimeString;
    
}

-(void)SDChatInputViewFrameWillChange:(SDChatInputView *)chatInputView{

    
//    self.chatTableView.frame =CGRectMake(0, 0, G_SCREENWIDTH, CGRectGetMinY(chatInputView.frame));
    
    [self sd_scrollToBottomWithAnimated:YES];
    SDLog(@"-----chatTableView2-----:%@",NSStringFromCGRect(self.chatTableView.frame))
}
#pragma mark - textFieldDelegate

-(void)SDChatDetailTableViewLongPress:(UILongPressGestureRecognizer *)longPressGr{
//           [self.chatInputView.chatTextFiled becomeFirstResponder];
}


#pragma mark - 监听键盘弹出方法
- (void)sd_scrollToBottomWithAnimated:(BOOL)animate
{
    SDChatDataModel * SD = [SDChatDataModel sharedSDChatDataModel];
    if (!SD.dataSource.count) return;
    [self scrollTableToFoot:YES];

}

//#pragma mark -右按钮
//-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//
//    [self.view endEditing:YES];
//    [self inputViewScrollToBottom];
//}

-(void)dealloc{
    [self stopTimer];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];

    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


-(void)setLab:(UILabel *)lab withColor:(UIColor *)color andFont:(CGFloat)font andText:(NSString *)text andTextAlignment:(NSTextAlignment)textAlignment{
    lab.text=text;
    lab.textColor=color;
    lab.font=[UIFont systemFontOfSize:font];
    lab.textAlignment=textAlignment;
}

#pragma mark-获取订单状态
-(void)GetOtcorderOrderStatus{
    
    NSString * URL = [NSString stringWithFormat:@"%@otcorder/orderStatus",DEFAULTSEVERBASEURL];
    
    
    NSDictionary * Dic  = @{
                            @"order_sn":_order_sn,
                            @"access_token":[LoginModel GetValue:DL_token]
                            };
    WS(weakSelf);
    [HUD showProgress:@"" inView:self.bgView];
    
    [MOLoadHttpsData PostHttpDataWithUrlStr:URL Dic:Dic SuccessBlock:^(id  _Nonnull responseObject) {
        [HUD dismissInView:weakSelf.bgView];
        
        NSDictionary * dic = responseObject;
        
        NSString * code = [NSString stringWithFormat:@"%@",dic[@"code"]];
        if ([code isEqualToString:@"0"]){
            NSDictionary * dicc = dic[@"data"];
            NSString * status = [NSString stringWithFormat:@"%@",dicc[@"status"]];
//            订单状态，@0：待付款；@1：已付款（未释放代币）；@2：已释放代币；@3：已完成；@4：已取消
            
            
            if ([status integerValue]==0) {
                weakSelf.status.text=@"待付款";
            }else if ([status integerValue]==1){
                weakSelf.status.text=@"已付款";
            }else if ([status integerValue]==2){
                weakSelf.status.text=@"已释放代币";
            }else if ([status integerValue]==3){
                weakSelf.status.text=@"已完成";
            }else if ([status integerValue]==4){
                weakSelf.status.text=@"已取消";
            }
        }else{
            
        }

    } FailureBlock:^(id  _Nonnull error) {
        [HUD dismissInView:weakSelf.bgView];

    }];
    
        
}

-(void)GetOtcorderFindorder{
    //    获取指定的订单信息（下单后调用）
    
    NSString * URL = [NSString stringWithFormat:@"%@otcorder/findorder",DEFAULTSEVERBASEURL];
   
    NSDictionary * Dic  = @{
                            @"order_sn":_order_sn,
                            @"access_token":[LoginModel GetValue:DL_token]
                            };
    WS(weakSelf);
    [HUD showProgress:@"" inView:self.bgView];
    [MOLoadHttpsData PostHttpDataWithUrlStr:URL Dic:Dic SuccessBlock:^(id  _Nonnull responseObject) {
        [HUD dismissInView:weakSelf.bgView];
        
        NSDictionary * dic = responseObject;
        
        NSString * code = [NSString stringWithFormat:@"%@",dic[@"code"]];
        NSString * msg = [NSString stringWithFormat:@"%@",dic[@"msg"]];
        if ([code isEqualToString:@"0"]){
            
            NSDictionary * dicc = dic[@"data"];
//            NSLog(@"-------%@",dicc);
            weakSelf.FindOrderModel = [FBFindorderModel mj_objectWithKeyValues:dicc];
            SDChatDataModel * SD = [SDChatDataModel sharedSDChatDataModel];
            SD.FindorderModel = weakSelf.FindOrderModel;
            weakSelf.symbol.text=[NSString stringWithFormat:@"%@",weakSelf.FindOrderModel.symbol];
            weakSelf.money.text=[NSString stringWithFormat:@"%@",weakSelf.FindOrderModel.amount];
            weakSelf.lab2.text=[NSString stringWithFormat:@"交易金额(%@)",weakSelf.FindOrderModel.legal];
            
            weakSelf.baseVcTitle=[NSString stringWithFormat:@"与%@聊天中...",weakSelf.FindOrderModel.bill_nickname];
            
            [weakSelf getTime];
            

            
        }else{
            [HUD showErrorMessage:msg];
        }
        
    } FailureBlock:^(id  _Nonnull error) {
        [HUD dismissInView:weakSelf.bgView];
        
    }];
}


-(void)getTime{
    
    _T = [self.FindOrderModel.over_time integerValue]-[[MOLoadHttpsData getCurrentTimestamp] integerValue];
    
    if (_T<0) {
        _T=0;
        [self stopTimer];
        self.time.text=@"0分0秒";
    }else{
        [self setUpTimer];
    }
}



-(void)TimerAction{
    
    _T--;
    if (_T<0||_T==0) {
        [self stopTimer];
    }else{
        
        self.time.text = [MOLoadHttpsData getMMSSFromSS:_T];
    }
}

#pragma mark-创建定时器
- (void)setUpTimer{
    [self stopTimer];
    WS(wself);
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:wself selector:@selector(TimerAction) userInfo:nil repeats:YES];
    self.orderTimer = timer;
    [[NSRunLoop mainRunLoop ] addTimer:timer forMode:NSRunLoopCommonModes];
    
}





- (void)stopTimer{
    //关闭定时器
    [self.orderTimer invalidate];
    
    self.orderTimer = nil;
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


-(void)createHeaderView{
 
    UIView * headerView = [[UIView alloc]init];
    [self.bgView addSubview:headerView];
    [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.bgView.mas_top).offset(10);
        make.right.left.equalTo(self.bgView);
        make.height.mas_equalTo(75);
    }];
    
    UILabel * lab1 = [[UILabel alloc]init];
    [self.bgView addSubview:lab1];
    [self setLab:lab1 withColor:RGB(140, 159, 173) andFont:12 andText:@"交易币种" andTextAlignment:NSTextAlignmentLeft];
    [lab1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(headerView.mas_top).offset(0);
        make.left.equalTo(self.bgView).offset(20);
        make.height.mas_equalTo(30);
        make.width.mas_equalTo(100);
    }];
    
    
    UILabel * symbol = [[UILabel alloc]init];
    [self.bgView addSubview:symbol];
    [self setLab:symbol withColor:RGB(30, 63, 89) andFont:15 andText:@"加载中" andTextAlignment:NSTextAlignmentLeft];
    [symbol mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(lab1.mas_bottom).offset(0);
        make.left.equalTo(self.bgView).offset(20);
        make.height.mas_equalTo(30);
        make.width.mas_equalTo(100);
    }];
    _symbol=symbol;
    
    UILabel * lab2 = [[UILabel alloc]init];
    [self.bgView addSubview:lab2];
    [self setLab:lab2 withColor:RGB(140, 159, 173) andFont:12 andText:@"交易金额" andTextAlignment:NSTextAlignmentCenter];
    [lab2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(headerView.mas_top).offset(0);
        make.left.right.equalTo(self.bgView);
        make.height.mas_equalTo(30);
        //        make.width.mas_equalTo(100);
    }];
    _lab2=lab2;
    
    UILabel * money = [[UILabel alloc]init];
    [self.bgView addSubview:money];
    [self setLab:money withColor:RGB(30, 63, 89) andFont:15 andText:@"加载中" andTextAlignment:NSTextAlignmentCenter];
    [money mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(lab2.mas_bottom).offset(0);
        make.left.right.equalTo(self.bgView);
        make.height.mas_equalTo(30);
        //        make.width.mas_equalTo(100);
    }];
    _money=money;
    
    UILabel * lab3 = [[UILabel alloc]init];
    [self.bgView addSubview:lab3];
    [self setLab:lab3 withColor:RGB(140, 159, 173) andFont:12 andText:@"加载中" andTextAlignment:NSTextAlignmentRight];
    [lab3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(headerView.mas_top).offset(0);
        make.right.equalTo(self.bgView).offset(-20);
        make.height.mas_equalTo(30);
        //        make.width.mas_equalTo(100);
    }];
    _status = lab3;
    
    UIImageView * timeimgV=[[UIImageView alloc]init];
    [headerView addSubview:timeimgV];
    timeimgV.image=[UIImage imageNamed:@"时间icon"];
    [timeimgV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(lab3.mas_centerY).offset(0);
        make.right.equalTo(lab3.mas_left).offset(-10);
        make.height.mas_equalTo(15);
        make.width.mas_equalTo(15);
    }];
    
    UILabel * time = [[UILabel alloc]init];
    [self.bgView addSubview:time];
    [self setLab:time withColor:RGB(30, 63, 89) andFont:12 andText:@"加载中" andTextAlignment:NSTextAlignmentRight];
    [time mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(lab3.mas_bottom).offset(0);
        make.right.equalTo(self.bgView).offset(-20);
        make.height.mas_equalTo(30);
        make.width.mas_equalTo(100);
    }];
    _time=time;
    UIView * line = [[UIView alloc]init];
    [headerView addSubview:line];
    line.backgroundColor=RGB(230, 234, 237);
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(headerView.mas_bottom).offset(0);
        make.right.left.equalTo(self.bgView);
        make.height.mas_equalTo(1);
        make.width.mas_equalTo(G_SCREENWIDTH);
    }];
    
    
}
@end
